import java.util.Arrays;
import java.util.Date;
import java.net.*;
import spread.*;

public class Consumer {

    public static void main(String[] args) {
        Consumer tool = new Consumer();
        tool.run();
    }

    public void run() {
		SpreadConnection connection = new SpreadConnection();
		try{
			InetAddress addr = InetAddress.getByName("localhost");
			System.out.println("Connecting to daemon :" + addr  );
			connection.connect(addr, 0, "consumer", false, false);
			SpreadGroup group = new SpreadGroup();
			group.join(connection, "group");
			System.out.println("Ready to receive group : " + group.toString() );
			
			long lowestSendTime=Long.MAX_VALUE;
			while(true)
			{
				SpreadMessage message = connection.receive();
				if(message.isRegular())
				{
					long aValues[] = (long [])message.getObject();
					long rcvTime = System.nanoTime();
					long transferTime = rcvTime - aValues[1];
					/*if( false ) 
					{
						// For System.nanoTime() to work it must be on same machine
						long relativeSendTime = rcvTime - aValues[1];
						if( relativeSendTime < lowestSendTime )
							lowestSendTime = relativeSendTime;
						transferTime = relativeSendTime - lowestSendTime
					}*/
					System.out.printf("Message from %s : %d after %.3f ms%n" , message.getSender() , aValues[0] , ((double)transferTime)/1000000 );
				}
				else
					System.out.println("Membership message from " + message.getMembershipInfo().getGroup() + " : " + message.toString() );
			}
		}catch( Exception e )
		{
			System.out.println("Exception : " + e );
		}
    }
}